package com.jumi.microservice.yzhpay.dto.request;

import com.jumi.microservice.yzhpay.constant.ConfigPath;
import com.jumi.microservice.yzhpay.constant.XmlData;
import com.jumi.microservice.yzhpay.util.DESUtil;
import com.jumi.microservice.yzhpay.util.JsonUtil;
import com.jumi.microservice.yzhpay.util.Property;
import com.jumi.microservice.yzhpay.util.RSAUtil;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.net.URLEncoder;
import java.util.Date;

/**
 * 示例：data=MhjTl1rWjFxHJ5e&mess=12313&timestamp=123457&sign=b6516baa210161df6f34f1efec2a7c484fd7920fed5640e066e970d8a3f01499&sign_type=rsa
 **/
@Getter
@Setter
@ToString
@Builder
public class Request<T> {

    /**
     * 时间戳，精确到秒
     **/
    private int timestamp = Integer.parseInt(String.valueOf(new Date().getTime()/1000));

    /**
     * 签名
     **/
    private String sign;

    /**
     * 签名方式，固定值rsa
     **/
    private String sign_type = Property.getProperties(ConfigPath.YZH_SIGN_TYPE);

    /**
     * 随机数，用于签名
     **/
    private String mess;

    /**
     * 经过加密后的具体数据
     **/
    private String data;

    public Request encData(T param) throws Exception {
        setData(DESUtil.encode(JsonUtil.toJson(param)));
        return this;
    }

    // 获取签名
    public String getSign() {
        String plain = new StringBuffer("data=")
                .append(data)
                .append("&mess=")
                .append(mess)
                .append("&timestamp=")
                .append(timestamp)
                .append("&key=")
                .append(Property.getProperties(ConfigPath.YZH_APPKEY))
                .toString();
        return RSAUtil.sign(plain, Property.getProperties(ConfigPath.YZH_RSA_PRIVATE_KEY));
    }

    // 获取get请求明文串
    public String getPlainEncode() throws Exception {
        return new StringBuffer("data=")
                .append(getEncode(data))
                .append("&mess=")
                .append(getEncode(mess))
                .append("&timestamp=")
                .append(timestamp)
                .append("&sign_type=")
                .append(getEncode(sign_type))
                .append("&sign=")
                .append(getEncode(getSign()))
                .toString();
    }

    private String getEncode(String content) throws Exception {
        return URLEncoder.encode(content, XmlData.CHARSET);
    }
}
